import api from "./api";
import constant from "./constant";
import { formatDateTime } from "../utils/util.js";

function getGioUser() {
  return getApp().globalData.loginPromise.then(({ sessionUser }) => {
    const extProps = sessionUser.extProps;
    const currentCity = wx.getStorageSync("currentCity");
    return {
      wxMobile: extProps.wxMobile || sessionUser.mobile || "",
      wechatUnionid: extProps.wechatUnionid,
      wechatOpenid: extProps.wechatOpenid,
      nickname: extProps.nickname || sessionUser.realName || "",
      city: (currentCity ? currentCity.city : extProps.loginCity) || "",
    };
  });
}

const pushTypeMap = {
  OWNPUSH: "面销",
  OUTSOURCEPUSH: "地推",
  JOINPUSH: "分销",
  ONLINEPUSH: "网销",
  COOPERATION_HOUSE: "合作房",
  WECHATMOMENTS: "朋友圈",
  FISSION: "裂变",
  OFFICIAL: "官方",
  OUTERCHAIN: "外链",
};
const verifyCooperationMap = {
  1: "待审核",
  2: "审核通过",
  3: "取消审核",
  4: "审核不通过",
};

export function getGioUserInfo() {
  return new Promise((resolve, reject) => {
    api.getGioUserInfo(null, ({ data }) => {
      if (data.isSuccess && data.content) {
        const info = data.content;

        const result = {
          internalUser: ["正常用户", "内部用户"][info.internalUser],
          memberEndDate: info.memberEndDate ? formatDateTime(info.memberEndDate) : "",
          pushType: pushTypeMap[info.pushType],
          saleServiceId: info.saleServiceId,
          saleServiceName: info.saleServiceName,
          verifierId: info.verifierId,
          verifierName: info.verifierName,
          verifyCooperation: verifyCooperationMap[info.verifyCooperation],
        };

        resolve(result);
      } else {
        resolve({});
      }
    });
  });
}

export function gio(eventName, params) {
  // 生产环境才上报
  // isReleaseUrl && wx.gio("track", eventName, params);
  wx.gio("track", eventName, params);
  console.log("埋点记录", eventName, params);
}

/** 登录用户变量
 * cb()  支持promise异步给值
 *  => {
 *  eventName: string '事件名称',
 *  params: object 额外的事件标识符及其值
 * }
 */

function gioLoginUserBase(cb) {
  return Promise.all([getGioUser()]).then(([gioUser]) => {
    let base = {
      [constant.Phone]: gioUser.wxMobile,
      [constant.UnionId_Var]: gioUser.wechatUnionid,
      [constant.openId]: gioUser.wechatOpenid,
      [constant.Wechat_Name]: gioUser.nickname,
      [constant.City_Ppl]: gioUser.city,
    };

    Promise.resolve()
      .then(() => {
        return cb();
      })
      .then(({ eventName, params }) => {
        const result = Object.assign(base, params);
        for (const key in result) {
          result[key] = result[key] || "";
        }

        gio(eventName, result);
      });
  });
}
/**
 * 基本信息埋点log
 * params 可选项
 *  */
export function gioBaseLog(eventName, params = {}) {
  gioLoginUserBase(() => {
    return {
      eventName,
      params,
    };
  });
}

/** 邀请者记录埋点 */
export function gioInviterLog(eventName, actEntre_var) {
  gioLoginUserBase(() => {
    const params = {
      [constant.ActEntre_Aar]: actEntre_var,
    };
    return {
      eventName,
      params,
    };
  });
}

/** 拉新裂变 活动引导埋点 */
export function gioFissionLog(eventName, scene_var) {
  gioLoginUserBase(() => {
    const params = {
      [constant.scene_var]: scene_var,
    };
    return {
      eventName,
      params,
    };
  });
}

/** 被邀请者新人埋点 */
export function gioNewUserLog(eventName, fromUserId, antreVar, showtime_var) {
  gioLoginUserBase(() => {
    const params = {
      [constant.InviteId_Ppl]: fromUserId,
      [constant.Entre_var]: antreVar,
    };
    if (showtime_var) {
      params[constant.showtime_var] = showtime_var;
    }

    return {
      eventName,
      params,
    };
  });
}

/** 认证消息已读事件 */
export function gioAuthReadedLog(phone, name) {
  gioLoginUserBase(() => {
    const params = {
      [constant.imPhone]: phone,
      [constant.imName]: name,
    };
    return {
      eventName: constant.imRead,
      params,
    };
  });
}

/** IM消息一键回拨 */
export function gioPhoneRecallLog(callType) {
  gioLoginUserBase(() => {
    const params = {
      [constant.callType]: callType,
    };
    return {
      eventName: constant.phoneRecall,
      params,
    };
  });
}

/** 触发客源认证信息弹窗 */
export function gioKeyuanLog(eventName, winFrom, infromWay) {
  gioLoginUserBase(() => {
    const params = {
      winFrom,
      infromWay,
    };
    return {
      eventName,
      params,
    };
  });
}
// 触发客源认证信息弹窗----设置定位事件
export function gioSetPositionLog(eventName, typeSet) {
  gioLoginUserBase(() => {
    const params = {
      typeSet,
    };
    return {
      eventName,
      params,
    };
  });
}

// 触发客源认证信息弹窗----关闭弹窗
export function gioCloseLog(eventName, havePosition, haveJpg) {
  gioLoginUserBase(() => {
    const params = {
      havePosition,
      haveJpg,
    };
    return {
      eventName,
      params,
    };
  });
}

/**
 * 合作房源tab埋点
 *  */
export function gioCooperationLog(eventName, userId, pageName) {
  gioLoginUserBase(() => {
    return new Promise((resolve, reject) => {
      api.queryUserAuthInfo({ userId }, ({ data }) => {
        const extra = pageName ? { pageName } : {};
        if (data && data.content) {
          resolve({ eventName, params: { [constant.userAuthed]: data.content.verified ? "Y" : "N", ...extra } });
        } else {
          resolve({ eventName, params: { [constant.userAuthed]: "", ...extra } });
        }
      });
    });
  });
}

/**
 * 会员相关
 */
export function gioVipLog(eventName, invitedId, orderEntr) {
  gioLoginUserBase(() => {
    const params = {
      [constant.InviteId_Ppl]: invitedId,
      [constant.OrderEntr_var]: orderEntr,
    };
    return {
      eventName,
      params,
    };
  });
}

/**
 * 成功支付
 */
export function gioPaySuccessLog(eventName, gioFromId, orderType, orderPay, bannerName) {
  gioLoginUserBase(() => {
    const params = {
      [constant.InviteId_Ppl]: gioFromId,
      [constant.OrderType_var]: orderType,
      [constant.OrderPay_var]: orderPay,
    };
    if (bannerName) {
      params[constant.BannerName_var] = bannerName;
    }
    return {
      eventName,
      params,
    };
  });
}

/**
 * 发送认证消息
 */
export function gioSendAuthLog(eventName, phone, name) {
  gioLoginUserBase(() => {
    const params = {
      [constant.imReceiverPhone]: phone,
      [constant.imReceiverName]: name,
    };
    return {
      eventName,
      params,
    };
  });
}
